import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { ReceiptOrderService } from './receipt-order.service';
import { ListService } from '@abp/ng.core';
import { ThemeSharedModule } from '@abp/ng.theme.shared';
import { ReceiptOrderCreateComponent } from './receipt-order-create.component';
import { ToasterService, ConfirmationService, Confirmation } from '@abp/ng.theme.shared';

@Component({
  selector: 'app-receipt-order',
  standalone: true,
  imports: [CommonModule, FormsModule, ThemeSharedModule, ReceiptOrderCreateComponent],
  styleUrls: ['./receipt-order.component.scss'],
  template: `
    <div class="card">
      <div class="card-header">
        <h5 class="card-title">收货登记</h5>
      </div>
      <div class="card-body">
        <!-- 搜索区域 -->
        <div class="row mb-3">
          <div class="col-md-2">
            <label class="form-label">到货通知单号</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.noticeNo">
          </div>
          <div class="col-md-2">
            <label class="form-label">客户订单号</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.customerNode">
          </div>
          <div class="col-md-2">
            <label class="form-label">商品编码</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.productCode">
          </div>
          <div class="col-md-2">
            <label class="form-label">商品名称</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.product">
          </div>
          <div class="col-md-2">
            <label class="form-label">托盘</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.tray">
          </div>
          <div class="col-md-2">
            <label class="form-label">储位</label>
            <input type="text" class="form-control" [(ngModel)]="searchParams.storageLocation">
          </div>
          <div class="col-md-2">
            <label class="form-label">货主</label>
            <select class="form-select" [(ngModel)]="searchParams.shipper">
              <option value="">--请选择--</option>
              <option *ngFor="let shipper of shippers" [value]="shipper.value">{{shipper.label}}</option>
            </select>
          </div>
          <div class="col-md-2">
            <label class="form-label">是否已上架</label>
            <select class="form-select" [(ngModel)]="searchParams.isShelved">
              <option value="">--请选择--</option>
              <option value="true">是</option>
              <option value="false">否</option>
            </select>
          </div>
        </div>

        <!-- 按钮区域 -->
        <div class="row mb-3">
          <div class="col">
            <button class="btn btn-primary me-2" (click)="search()">
              <i class="fa fa-search me-1"></i>查询
            </button>
            <button class="btn btn-secondary" (click)="reset()">
              <i class="fa fa-redo me-1"></i>重置
            </button>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="row mb-3">
          <div class="col">
            <button class="btn btn-success me-2" (click)="showCreateModal = true">
              <i class="fa fa-plus me-1"></i>录入
            </button>
            <button class="btn btn-info me-2" (click)="edit()">
              <i class="fa fa-edit me-1"></i>编辑
            </button>

            <button class="btn btn-success me-2" (click)="batchShelf()">
              <i class="fa fa-check me-1"></i>批量上架
            </button>
            <input type="file" #importInput style="display:none" (change)="importReceiptOrders($event)">


            <button class="btn btn-info me-2" [disabled]="selectedCount !== 1" (click)="view()">
              <i class="fa fa-search me-1"></i>查看
            </button>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-responsive">
          <table class="table table-striped table-hover">
            <thead>
              <tr>
                <th>
                  <input type="checkbox" [(ngModel)]="isAllSelected" (change)="toggleSelectAll()">
                </th>
                <th>操作</th>
                <th>验收人</th>
                <th>到货通知单号</th>
                <th>客户订单号</th>
                <th>商品名称</th>
                <th>到货数量</th>
                <th>数量</th>
                <th>箱注</th>
                <th>温度</th>
                <th>生产日期</th>
                <th>批次</th>
                <th>托盘</th>
                <th>单位</th>
                <th>储位</th>
                <th>体积</th>
                <th>重量</th>
                <th>货主</th>
                <th>是否已上架</th>
              </tr>
            </thead>
            <tbody>
              <tr *ngFor="let item of receiptOrders">
                <td>
                  <input type="checkbox" 
                         [(ngModel)]="item.selected"
                         (change)="updateSelectAll()">
                </td>
                <td>
                  <button class="btn btn-sm btn-danger me-1" (click)="delete(item)">
                    删除
                  </button>
                  <button class="btn btn-sm btn-primary" (click)="shelfUp(item)">
                    上架
                  </button>
                </td>
                <td>{{item.receiver}}</td>
                <td>{{item.noticeNo}}</td>
                <td>{{item.customerNode}}</td>
                <td>{{productMap[item.product] || item.product}}</td>
                <td>{{item.arrivalQty}}</td>
                <td>{{item.qty}}</td>
                <td>{{item.remark}}</td>
                <td>{{item.receiptTemperature}}</td>
                <td>{{item.productionDate | date:'yyyy-MM-dd'}}</td>
                <td>{{item.batch}}</td>
                <td>{{item.tray}}</td>
                <td>{{item.unit}}</td>
                <td>{{item.storageLocation}}</td>
                <td>{{item.volume}}</td>
                <td>{{item.weight}}</td>
                <td>{{ getShipperLabel(item.shipper) }}</td>
                <td>{{item.isShelved ? '是' : '否'}}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 分页区域 -->
        <div class="row">
          <div class="col-sm-12 col-md-5">
            <div class="dataTables_info" role="status" aria-live="polite">
              显示第 {{(currentPage - 1) * pageSize + 1}} 至 
              {{Math.min(currentPage * pageSize, totalItems)}} 条
              共 {{totalItems}} 条记录
            </div>
          </div>
          <div class="col-sm-12 col-md-7">
            <div class="dataTables_paginate paging_simple_numbers">
              <ul class="pagination justify-content-end">
                <li class="paginate_button page-item previous" [class.disabled]="currentPage === 1">
                  <a class="page-link" href="javascript:void(0)" (click)="pageChange(currentPage - 1)">
                    上一页
                  </a>
                </li>
                <li class="paginate_button page-item" 
                    *ngFor="let page of pages" 
                    [class.active]="page === currentPage">
                  <a class="page-link" href="javascript:void(0)" (click)="pageChange(page)">
                    {{page}}
                  </a>
                </li>
                <li class="paginate_button page-item next" 
                    [class.disabled]="currentPage === totalPages">
                  <a class="page-link" href="javascript:void(0)" (click)="pageChange(currentPage + 1)">
                    下一页
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <!-- 创建弹窗 -->
        <app-receipt-order-create 
          *ngIf="showCreateModal"
          [editMode]="editMode"
          [editModel]="editModel"
          [viewMode]="viewMode"
          (modalClosed)="onModalClose($event)">
        </app-receipt-order-create>
      </div>
    </div>
  `,
  providers: [ListService]
})
export class ReceiptOrderComponent implements OnInit {
  showCreateModal = false;
  editMode = false;
  editModel: any = null;
  viewMode = false;

  // 搜索参数
  searchParams = {
    noticeNo: '',
    customerNode: '',
    productCode: '',
    product: '',
    tray: '',
    storageLocation: '',
    shipper: '',
    isShelved: ''
  };

  // 货主列表
  shippers = [
    { value: 'HZ001', label: '001-胡适业001' },
    { value: 'HZ002', label: '002-京东物流' },
    { value: 'HZ003', label: '003-顺丰速运' },
    { value: 'HZ004', label: '004-阿里物流' },
    { value: 'HZ005', label: '005-菜鸟物流' },
    { value: 'HZ006', label: '006-德邦快递' },
    { value: 'HZ007', label: '007-圆通速递' },
    { value: 'HZ008', label: '008-中通快递' },
    { value: 'HZ009', label: '009-韵达快递' },
    { value: 'HZ010', label: '010-申通快递' }
  ];

  // 表格数据
  receiptOrders: any[] = [];
  isAllSelected = false;

  // 分页参数
  currentPage = 1;
  pageSize = 10;
  totalItems = 0;
  totalPages = 1;
  pages: number[] = [];
  Math = Math;

  productMap: { [id: string]: string } = {};

  constructor(
    private receiptOrderService: ReceiptOrderService,
    private toaster: ToasterService,
    private confirmation: ConfirmationService
  ) {}

  ngOnInit() {
    this.loadProductMap();
    this.loadData();
  }

  loadProductMap() {
    this.receiptOrderService.getProductList().subscribe(res => {
      if (res && Array.isArray(res.items)) {
        this.productMap = {};
        res.items.forEach(item => {
          this.productMap[item.id] = item.productName;
        });
      }
    });
  }

  // 加载数据
  loadData() {
    this.receiptOrderService.getList({
      ...this.searchParams,
      skipCount: (this.currentPage - 1) * this.pageSize,
      maxResultCount: this.pageSize
    }).subscribe(response => {
      this.receiptOrders = response.items;
      this.totalItems = response.totalCount;
      this.calculatePages();
    });
  }

  // 计算分页
  calculatePages() {
    this.totalPages = Math.ceil(this.totalItems / this.pageSize);
    this.pages = Array.from({length: this.totalPages}, (_, i) => i + 1);
  }

  // 搜索
  search() {
    this.receiptOrderService.getByConditions(this.searchParams).subscribe(response => {
      this.receiptOrders = response.items;
      this.totalItems = response.totalCount || (response.items ? response.items.length : 0);
      this.calculatePages && this.calculatePages();
    });
  }

  // 重置
  reset() {
    this.searchParams = {
      noticeNo: '',
      customerNode: '',
      productCode: '',
      product: '',
      tray: '',
      storageLocation: '',
      shipper: '',
      isShelved: ''
    };
    this.search();
  }

  // 切换全选
  toggleSelectAll() {
    this.receiptOrders.forEach(item => item.selected = this.isAllSelected);
  }

  // 更新全选状态
  updateSelectAll() {
    this.isAllSelected = this.receiptOrders.every(item => item.selected);
  }

  // 删除
  delete(item: any) {
    if (item.id) {
      this.confirmation.warn(
        '确定要删除该收货记录吗？',
        '删除确认',
        { messageLocalizationParams: [] }
      ).subscribe((status) => {
        if (status === Confirmation.Status.confirm) {
          this.receiptOrderService.delete(item.id).subscribe(() => {
            this.toaster.success('删除成功');
            this.loadData();
          });
        }
      });
    }
  }

  // 上架
  shelfUp(item: any) {
    if (item.isShelved) {
      this.toaster.warn('该记录已上架');
      return;
    }
    if (item.id) {
      this.receiptOrderService.shelfUp(item.id).subscribe(() => {
        item.isShelved = true;
        this.toaster.success('上架成功');
        this.loadData();
      });
    }
  }

  // 页码变化
  pageChange(page: number) {
    if (page >= 1 && page <= this.totalPages) {
      this.currentPage = page;
      this.loadData();
    }
  }

  // 编辑
  edit() {
    const selected = this.receiptOrders.filter(item => item.selected);
    if (selected.length !== 1) {
      this.toaster.warn('请只勾选一条要编辑的数据');
      return;
    }
    this.editMode = true;
    // 深拷贝，避免直接修改表格数据
    this.editModel = JSON.parse(JSON.stringify(selected[0]));
    this.showCreateModal = true;
  }

  // 查看
  view() {
    const selected = this.receiptOrders.filter(item => item.selected);
    if (selected.length !== 1) {
      this.toaster.warn('请只勾选一条要查看的数据');
      return;
    }
    this.editMode = false;
    this.viewMode = true;
    this.editModel = JSON.parse(JSON.stringify(selected[0]));
    this.showCreateModal = true;
  }

  onModalClose(result: boolean) {
    this.showCreateModal = false;
    this.editMode = false;
    this.viewMode = false;
    this.editModel = null;
    if (result) {
      this.loadData();
    }
  }

  get selectedCount() {
    return this.receiptOrders.filter(item => item.selected).length;
  }

  getShipperLabel(value: string): string {
    const found = this.shippers.find(s => s.value === value);
    return found ? found.label : value;
  }

  // 批量上架
  batchShelf() {
    const checked = this.receiptOrders.filter(item => item.selected);
    if (checked.length === 0) {
      this.toaster.warn('请先选择商品');
      return;
    }
    const notShelved = checked.filter(item => !item.isShelved);
    if (notShelved.length === 0) {
      this.toaster.info('商品已经上架了');
      return;
    }
    const ids = notShelved.map(item => item.id);
    this.receiptOrderService.batchShelf(ids).subscribe(() => {
      this.toaster.success('批量上架成功');
      this.loadData();
    });
  }

  // 导出
  exportReceiptOrders() {
    const checked = this.receiptOrders.filter(item => item.selected);
    let params: any = this.searchParams;
    if (checked.length > 0) {
      params = { ids: checked.map(item => item.id) };
    }
    this.receiptOrderService.exportReceiptOrders(params).subscribe(blob => {
      const a = document.createElement('a');
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = '收货单导出.xlsx';
      a.click();
      window.URL.revokeObjectURL(url);
    });
  }

  // 导入
  importReceiptOrders(event: any) {
    const file = event.target.files[0];
    if (!file) return;
    const formData = new FormData();
    formData.append('file', file);
    this.receiptOrderService.importReceiptOrders(formData).subscribe(() => {
      this.toaster.success('导入成功');
      this.loadData();
    });
  }
} 